﻿<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="edit.aspx.cs" Inherits="StoreWeb.system.order.edit" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <meta charset="utf-8">
    <meta name="renderer" content="webkit|ie-comp|ie-stand">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no" />
    <meta http-equiv="Cache-Control" content="no-siteapp" />
    <!--[if lt IE 9]>
<script type="text/javascript" src="../../lib/html5.js"></script>
<script type="text/javascript" src="../../lib/respond.min.js"></script>
<script type="text/javascript" src="../../lib/PIE_IE678.js"></script>
<![endif]-->
    <link href="../../css/H-ui.min.css" rel="stylesheet" type="text/css" />
    <link href="../../css/H-ui.admin.css" rel="stylesheet" type="text/css" />
    <link href="../../css/style.css" rel="stylesheet" type="text/css" />
    <link href="../../lib/Hui-iconfont/1.0.1/iconfont.css" rel="stylesheet" type="text/css" />
    <link href="../../css/album.css" rel="stylesheet" />
    <link href="../../css/menu.css" rel="stylesheet" />
    <link href="../../css/jquery.autocomplete.css" rel="stylesheet" />
    <link href="../../css/order.css" rel="stylesheet" />
    <script type="text/javascript" src="../../lib/jquery/1.9.1/jquery.min.js"></script>
    <script type="text/javascript" src="../../lib/layer/1.9.3/layer.js"></script>
    <link href="../../lib/webuploader/0.1.5/webuploader.css" rel="stylesheet" type="text/css" />
    <script type="text/javascript" src="../../lib/webuploader/0.1.5/webuploader.js"></script>
    <!--[if IE 6]>
<script type="text/javascript" src="lib/DD_belatedPNG_0.0.8a-min.js" ></script>
<script>DD_belatedPNG.fix('*');</script>
<![endif]-->
    <style type="text/css">
        .searchContainer,
        .searchContainer ul,
        .searchContainer li {
            width: 100%;
        }

        .searchContainer {
            position: relative;
            padding-top: 5px;
        }

            .searchContainer li {
                height: 25px;
                line-height: 25px;
                display: none;
            }

                .searchContainer li .title,
                .searchContainer li .list,
                .searchContainer li .list a {
                    float: left;
                    display: inline;
                }

                    .searchContainer li .title,
                    .searchContainer li .list a {
                        margin-left: 10px;
                    }

                .searchContainer li .list {
                    width: 400px;
                }

                    .searchContainer li .list a {
                        margin-bottom: 10px;
                        height: 25px;
                        line-height: 25px;
                        padding: 0 10px;
                        border: 1px solid #c9c9c9;
                    }

                        .searchContainer li .list a:hover,
                        .searchContainer li .list a.active {
                            color: #333;
                            border: 1px solid #ff4400;
                            text-decoration: none;
                        }

            .searchContainer .arrow {
                position: absolute;
                top: 5px;
                right: 5px;
                display: block;
                width: 30px;
                height: 30px;
                background: url(../../images/arrow-bottom.jpg) center no-repeat;
            }

                .searchContainer .arrow.top {
                    background: url(../../images/arrow-top.jpg) center no-repeat;
                }

            .searchContainer .clear {
                clear: both;
            }

        .leftContainer div.listContainer,
        .leftContainer ul.image {
            float: left;
            overflow-x: hidden;
            overflow-y: auto;
        }

        .leftContainer div.listContainer {
            width: 130px;
            border-right: 1px solid #eee;
        }

        .leftContainer ul.list li {
            float: left;
            width: 100%;
            height: 28px;
            line-height: 28px;
            font-size: 12px;
            text-indent: 10px;
            cursor: pointer;
        }

            .leftContainer ul.list li.active {
                background: #eee;
            }

        .leftContainer ul.image {
            width: 260px;
            padding: 0 3px 0 5px;
        }

            .leftContainer ul.image li,
            .leftContainer ul.image li img {
                float: left;
            }

            .leftContainer ul.image li {
                width: 68px;
                height: 104px;
                overflow: hidden;
                margin: 5px 5px 0 5px;
                cursor: pointer;
            }

                .leftContainer ul.image li .image {
                    border: 1px solid #fff;
                }

                .leftContainer ul.image li.active .image {
                    border: 1px solid #ff4400;
                }

                .leftContainer ul.image li .image,
                .leftContainer ul.image li .image img {
                    width: 66px;
                    height: 66px;
                }

                .leftContainer ul.image li .text {
                    width: 68px;
                    height: 36px;
                    overflow: hidden;
                    line-height: 18px;
                    font-size: 12px;
                }

        .overflowdiv {
            overflow-x: hidden;
            overflow-y: auto;
        }

        .displaynone {
            display: none;
        }

        .displayblock {
            display: block;
        }
    </style>

    <title>修改尺寸</title>
</head>
<body>
    <form id="formmemberadd" runat="server">
        <div class="sub-menu" style="margin: 5px;">
            <div class="content-menu">
                <div>
                    <span id="sizestd1"></span>
                    <span id="size1"></span>
                </div>
                <div>
                    <span id="sizestd2"></span>
                    <span id="size2"></span>
                </div>
                <div id="tetisize1" style="margin-top: 20px;">
                </div>
                <div id="tetisize2" style="margin-top: 20px;">
                </div>
            </div>
        </div>
        <div>
            <div class="row cl" style="margin-bottom: 5px;">
                <div class="formControls col-12">
                    <div class="uploader-list-container">
                        <div class="queueList">
                            <div id="dndArea" class="placeholder" style="min-height: 0px;">
                                <div id="filePicker-2"></div>
                                <p>或将图片附件拖到这里,可上传多张</p>
                            </div>
                        </div>
                        <div class="statusBar" style="display: none;">
                            <div class="progress"><span class="text">0%</span> <span class="percentage"></span></div>
                            <div class="info"></div>
                            <div class="btns">
                                <div id="filePicker2"></div>
                                <div class="uploadBtn">开始上传</div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div>
            <textarea id="txtnote" cols="100" rows="2" runat="server" style="height: 100px;" class="input-text" placeholder="请输入备注信息(非必填)"></textarea>
        </div>
        <div class="row cl" style="margin-top: 20px;">
            <div class="col-10 col-offset-2">
                <asp:HiddenField ID="hidid" runat="server" />
                <input type="button" id="btnok" class="btn btn-success radius" value="确定" />
            </div>
        </div>
        <input type="hidden" id="hidcInvCName" runat="server" />

        <input type="hidden" id="hdclnvCNames" runat="server" />
        <input type="hidden" id="hdcinvstd" runat="server" />
        <input type="hidden" id="hdcinvstd2" runat="server" />
        <input type="hidden" id="hdsize2" runat="server" />
        <input type="hidden" id="hdistz" runat="server" />
        <input type="hidden" id="hdsize" runat="server" />

        <input type="hidden" id="hdmobile" runat="server" />
        <input type="hidden" id="hidsize" runat="server" /><%--尺寸信息json--%>
        <input type="hidden" id="hidtetisize" runat="server" /><%--特体处理json--%>
        <input type="hidden" id="hidordercode" runat="server" /><%--订单编号--%>
        <input type="hidden" id="hidcInvCCode" runat="server" />
        <input type="hidden" id="hidurls" runat="server" /><%--附件图片--%>
    </form>
    <script type="text/javascript" src="../../lib/Validform/5.3.2/Validform.min.js"></script>
    <script type="text/javascript" src="../../lib/My97DatePicker/WdatePicker.js"></script>
    <script type="text/javascript" src="../../js/H-ui.js"></script>
    <script type="text/javascript" src="../../js/H-ui.admin.js"></script>
    <script src="../../js/sl.js"></script>
    <script src="../../js/jquery.album.slide.js"></script>
    <script src="../../js/menu.js"></script>
    <script type="text/javascript">
        function loadview()
        {
            //如果是套装
            if($("#hdistz").val()=="1")
            {
                getcinvstd($("#hdclnvCNames").val().split(',')[0],$("#hdcinvstd").val(),$("#hdsize").val(),1);
                getcinvstd($("#hdclnvCNames").val().split(',')[1],$("#hdcinvstd2").val(),$("#hdsize2").val(),2);
            }else
            {
                getcinvstd($("#hdclnvCNames").val().split(',')[0],$("#hdcinvstd").val(),$("#hdsize").val(),1);
            }
        }
        $(function () {
            loadview();
            $("#formmemberadd").Validform({
                tiptype: 2,
                btnSubmit: "#btnok",
                //callback: function (form) {
                //    form[0].submit();
                //    var index = parent.layer.getFrameIndex(window.name);
                //    parent.$('.btn-refresh').click();
                //    parent.layer.close(index);
                //}
                //,
                beforeSubmit: function (curform) {
                    sizedetail();//获取尺寸信息
                    $(".filelist .imgWrap2 img").each(function(){
                        if ($("#hidurls").val() == "") {
                            $("#hidurls").val($(this).attr("src"));
                        } else {
                            $("#hidurls").val($("#hidurls").val() + "|" + $(this).attr("src"));
                        }
                    });
                    $.post("../../ajax/order.aspx", {action:"updateorder", id: $("#hidid").val(),urls:$("#hidurls").val(),content:$("#txtnote").val(),size:$("#productsize").val(), hidsize: $("#hidsize").val(), hidtetisize: $("#hidtetisize").val()},
                    function (data) {
                        if (data == 1) {
                            parent.layer.alert("修改成功", function () {
                                parent.location.reload();
                            });
                        }  else {
                            parent.layer.msg("修改失败");
                        }
                    });
                    return false;
                }
            });
        });
        //获取尺寸信息
        function sizedetail()
        {
            var json = [];
            var tetijson = [];
            //获取具体尺寸
            $("#tablesize1>tbody>tr").each(function(){
                var item=$(this).find("input").data("item");
                $.extend(item,{tzgroup:1,ordercode:$("#hidordercode").val(),note:$("#szbz"+item.sizeid).html(),shetnote:$("#szbzbackup"+item.sizeid).html(),sizevalue:$(this).find("input").val(),cInvCCode:$("#hidcInvCCode").val(),hidcInvCName:($("#hidcInvCName").val()=="西服套装"?"西服上衣":$("#hidcInvCName").val())});
                json.push(item);
            });
            //获取套装情况尺寸
            $("#tablesize2>tbody>tr").each(function(){
                var item=$(this).find("input").data("item");
                $.extend(item,{tzgroup:2,ordercode:$("#hidordercode").val(),note:$("#szbz"+item.sizeid).html(),shetnote:$("#szbzbackup"+item.sizeid).html(),sizevalue:$(this).find("input").val(),cInvCCode:$("#hidcInvCCode").val(),hidcInvCName:($("#hidcInvCName").val()=="西服套装"?"西裤":$("#hidcInvCName").val())});
                json.push(item);
            });
            $("#hidsize").val(JSON.stringify(json));//保存尺寸信息
            //获取特体信息
            $("#tabletetisize1>tbody tr td").each(function(){
                var teti = {};
                $.extend(teti,{tzgroup:1,ordercode:$("#hidordercode").val(),groupname:$(this).find("span").html(),tetiid:$(this).find("select").val(),code:$(this).find("select").find("option:selected").text(),cInvCCode:$("#hidcInvCCode").val(),hidcInvCName:($("#hidcInvCName").val()=="西服套装"?"西服上衣":$("#hidcInvCName").val())});
                tetijson.push(teti);
            });
            //获取套装特体信息
            $("#tabletetisize2>tbody tr td").each(function(){
                var teti = {};
                $.extend(teti,{tzgroup:2,ordercode:$("#hidordercode").val(),groupname:$(this).find("span").html(),tetiid:$(this).find("select").val(),code:$(this).find("select").find("option:selected").text(),cInvCCode:$("#hidcInvCCode").val(),hidcInvCName:($("#hidcInvCName").val()=="西服套装"?"西裤":$("#hidcInvCName").val())});
                tetijson.push(teti);
            });
            $("#hidtetisize").val(JSON.stringify(tetijson));//保存特体处理
        }
        //根据分类名称获取规格型号
        function getcinvstd(clnvCName, cinvstd, size, num) {
            //alert(cinvstd);
            $.ajax({
                type: "POST",
                url: "../../ajax/order.aspx?action=getxinghaobycinvcname&cinvcname=" + clnvCName,
                success: function (data) {
                    var $select = $("<select></select>").off("change")
                            .on("change", function () {
                                getsize($(this).val(), num, "");
                                gettetisize($(this).val(), num);
                            });
                    $.each(JSON.parse(data), function (i, item) {
                        $("<option value='" + item.cinvstd + "' " + (cinvstd == item.cinvstd ? "selected='selected'" : "") + ">" + item.cinvstd + "</option>")
                            .appendTo($select);
                    });
                    getsize(cinvstd, num, size);//初始化尺寸
                    gettetisize(cinvstd, num);//初始化特体尺寸
                    $("#sizestd" + num).html($select);
                }
            });
        }
        //获取商品尺寸
        function getsize(cInvStd, num, size) {
            $.ajax({
                url: "../../ajax/product.aspx?cInvStd=" + cInvStd + "&size=" + size + "&action=getsizelist",
                dataType: "json",
                success: function (data) {
                    var container = $("#size" + num).empty();
                    if (data.sizelist.length) {
                        var select = $("<select id='productsize'></select>").off("change").on("change", function () {
                            getsizelist(cInvStd, $(this).val(), num);
                        }).appendTo(container);
                        $.each(data.sizelist, function (n, item) {
                            if(item.code==$("#hdsize").val())
                                $("<option></option>").attr("selected","selected").attr("value", item.code).html(item.code).appendTo(select);
                            else
                                $("<option></option>").attr("value", item.code).html(item.code).appendTo(select);
                        });
                        var table = $("<table></table>").attr("id", "tablesize" + num).appendTo(container);
                        if ($("#hidcInvCName").val() == "西服套装") {
                            var name = "西服套装";
                            $("<thead><tr></tr></thead>")
                                .append("<td>" + name + "尺寸</td>")
                                .append("<td>参考尺寸</td>")
                                .append("<td>成衣尺寸</td>")
                                .append("<td>备注</td>")
                                .appendTo(table);
                        } else {
                            $("<thead><tr></tr></thead>")
                                .append("<td>" + $("#hidcInvCName").val() + "尺寸</td>")
                                .append("<td>参考尺寸</td>")
                                .append("<td>成衣尺寸</td>")
                                .append("<td>备注</td>")
                                .appendTo(table);
                        }
                        $.each(data.list, function (n, item) {
                            var $table = $("<table style='width:70px;'></table>");
                            var $tr = $("<tr></tr>").appendTo($table);
                            var td1 = $("<td></td>")
                                .appendTo($tr);
                            $("<a></a>")
                                .addClass("shopcart-disc")
                                .off("click")
                                .on("click", function () {
                                    delnum(item.id, item.value, item.minpx);
                                })
                                .appendTo(td1);
                            var td2 = $("<td></td>")
                                .appendTo($tr);
                            $("<input style='WIDTH: 35px; HEIGHT: 15px'\">")
                                .addClass("inpcls2 ordersize")
                                .attr("id", "szvl" + item.id)
                                .attr("value", item.value)
                                .data("item", {
                                    sizeid: item.id,
                                    sizecode: item.code,
                                    sizename: item.name,
                                    backupsize:item.value
                                })
                                .off("blur")
                                .on("blur", function () {
                                    checksize(item.id, item.value, item.minpx, item.maxpx);
                                })
                                .appendTo(td2);
                            var td3 = $("<td></td>")
                                .appendTo($tr);
                            $("<a></a>")
                                .addClass("shopcart-add")
                                .off("click")
                                .on("click", function () {
                                    addnum(item.id, item.value, item.maxpx);
                                })
                                .appendTo(td3);
                            var tr = $("<tr></tr>")
                                 .append("<td>" + item.name + "</td>")
                                 .append("<td>" + item.value + "</td>")
                                .appendTo(table);
                            $("<td></td>")
                                .append($table)
                                .appendTo(tr);
                            $("<td><span id='szbz"+item.id+"'></span><span  id='szbzbackup"+item.id+"'>"+item.note+"</span></td>")
                                .appendTo(tr);
                        });
                        $.ajax({
                            url: "../../ajax/order.aspx?id=" + $("#hidid").val()+ "&tzgroup="+num+"&action=getordersize",
                            dataType: "json",
                            success: function (data2) {
                                $.each(data2, function (j, it) {
                                    $("#szvl" + it.sizeid).val(it.sizevalue);
                                    $("#szbz" + it.sizeid).html(it.note);
                                    $("#szbzbackup" + it.sizeid).html(it.shetnote);
                                });
                            }
                        });
                    }
                    else
                        container.html("暂无尺寸信息");
                }
            });
        }
        //获取具体尺寸
        function getsizelist(cInvStd, size, num) {
            $.ajax({
                url: "../../ajax/product.aspx?cInvStd=" + cInvStd + "&size=" + size + "&action=getsizelist",
                dataType: "json",
                success: function (data) {
                    var container = $("#tablesize" + num).empty();
                    if (data.sizelist.length) {
                        var table = $("<table></table>").attr("id", "tablesize" + num).appendTo(container);
                        if ($("#hidcInvCName").val() == "西服套装") {
                            var name = "西服套装";
                            $("<thead><tr></tr></thead>")
                                .append("<td>" + name + "尺寸</td>")
                                .append("<td>参考尺寸</td>")
                                .append("<td>成衣尺寸</td>")
                                .append("<td>备注</td>")
                                .appendTo(table);
                        } else {
                            $("<thead><tr></tr></thead>")
                                .append("<td>" + $("#hidcInvCName").val() + "尺寸</td>")
                                .append("<td>参考尺寸</td>")
                                .append("<td>成衣尺寸</td>")
                                .append("<td>备注</td>")
                                .appendTo(table);
                        }
                        $.each(data.list, function (n, item) {
                            var $table = $("<table style='width:70px;'></table>");
                            var $tr = $("<tr></tr>").appendTo($table);
                            var td1 = $("<td></td>")
                                .appendTo($tr);
                            $("<a></a>")
                                .addClass("shopcart-disc")
                                .off("click")
                                .on("click", function () {
                                    delnum(item.id, item.value, item.minpx);
                                })
                                .appendTo(td1);
                            var td2 = $("<td></td>")
                                .appendTo($tr);
                            $("<input style='WIDTH: 35px; HEIGHT: 15px'\">")
                                .addClass("inpcls2 ordersize")
                                .attr("id", "szvl" + item.id)
                                .attr("value", item.value)
                                .data("item", {
                                    sizeid: item.id,
                                    sizecode: item.code,
                                    sizename: item.name,
                                    backupsize:item.value
                                })
                                .off("blur")
                                .on("blur", function () {
                                    checksize(item.id, item.value, item.minpx, item.maxpx);
                                })
                                .appendTo(td2);
                            var td3 = $("<td></td>")
                                .appendTo($tr);
                            $("<a></a>")
                                .addClass("shopcart-add")
                                .off("click")
                                .on("click", function () {
                                    addnum(item.id, item.value, item.maxpx);
                                })
                                .appendTo(td3);
                            var tr = $("<tr></tr>")
                                 .append("<td>" + item.name + "</td>")
                                 .append("<td>" + item.value + "</td>")
                                .appendTo(table);
                            $("<td></td>")
                                .append($table)
                                .appendTo(tr);
                            $("<td><span id='szbz"+item.id+"'></span><span  id='szbzbackup"+item.id+"'>"+item.note+"</span></td>")
                                .appendTo(tr);
                        });
                    }
                    else
                        container.html("暂无尺寸信息");
                }
            });
        }
        //获取特体尺寸
        function gettetisize(cInvStd, num) {
            $.ajax({
                url: "../../ajax/product.aspx?cInvStd=" + cInvStd + "&action=gettetisizegroupby",
                dataType: "json",
                success: function (data) {
                    var list = "";
                    if ($("#hidcInvCName").val() == "西服套装")
                        list += "<table id=\"tabletetisize" + num + "\"><thead><tr><td style=\"background:#cccccc\" colspan=\"4\">" + (num == 1 ? "西服上衣" : "西裤") + "特体处理</td></tr></thead><tbody>";
                    else
                        list += "<table id=\"tabletetisize" + num + "\"><thead><tr><td style=\"background:#cccccc\" colspan=\"4\">" + $("#hidcInvCName").val() + "特体处理</td></tr></thead><tbody>";
                    $.each(data, function (n, item) {
                        if (n % 4 == 0)
                            list += "<tr class=\"text-c\">";
                        if (n + 1 == data.length)
                            list += "<td style=\"text-align: left\" colspan=\"" + (4 - (n % 4)) + "\"><span>" + item.groupname + "</span>";
                        else
                            list += "<td style=\"text-align: left\"><span>" + item.groupname + "</span>";
                        list += "&nbsp;<select id='tetiseze" +num+ item.groupname + "'>";

                        for (var i = 0; i < item.codelist.length; i++) {
                            list += "<option value=\"" + item.codelist[i] + "\">" + item.codelist[i] + "</option>";
                        }
                        list += "</select>";
                        list += "</td>";
                        if ((n != 0 && n % 4 == 0) || n + 1 == data.length)
                            list += "</tr>";
                    });
                    list += "</tbody></table>"
                    $("#tetisize" + num + "").html(list);
                    //初始化特体尺寸
                    $.each(<%=tetisizes%>, function (j, it) {
                        if(it.tzgroup==num)
                            $("#tetiseze"+num + it.groupname).val(it.code);
                    });
                }
            });
        }
        function delnum(id, value, minpx) {
            var vl = parseFloat($("#szvl" + id + "").val()) - 1;//当前数值-1
            if (Math.abs(vl - value) > parseFloat(minpx))
                alert("最小偏差不能大于" + minpx);
            else {
                $("#szbz" + id + "").html((vl-value).toFixed(2));
                $("#szvl" + id + "").val(vl);//设置当前
            }
        }
        function addnum(id, value, maxpx) {
            var vl = parseFloat($("#szvl" + id + "").val()) + 1;//当前数值+1
            if (vl - value > parseFloat(maxpx))
                alert("最大偏差不能大于" + maxpx);
            else {
                $("#szbz" + id + "").html((vl-value).toFixed(2));
                $("#szvl" + id + "").val(vl);//设置当前
            }
        }
        function checksize(id, value, minpx, maxpx) {
            var vl = parseFloat($("#szvl" + id + "").val());//当前数值
            if (Math.abs(vl - value) > parseFloat(minpx) || vl - value > parseFloat(maxpx)) {
                alert("最小偏差不能大于" + minpx + "且最大偏差不能大于" + maxpx);
                $("#szvl" + id + "").val(value);//设置当前
            }
            else {
                $("#szbz" + id + "").html((vl-value).toFixed(2));
            }
        }
        
        (function ($) {

            // 当domReady的时候开始初始化
            $(function () {
                var $wrap = $('.uploader-list-container'),

                    // 图片容器
                    $queue = $('<ul class="filelist"></ul>')
                        .appendTo($wrap.find('.queueList')),

                    // 状态栏，包括进度和控制按钮
                    $statusBar = $wrap.find('.statusBar'),

                    // 文件总体选择信息。
                    $info = $statusBar.find('.info'),

                    // 上传按钮
                    $upload = $wrap.find('.uploadBtn'),

                    // 没选择文件之前的内容。
                    $placeHolder = $wrap.find('.placeholder'),

                    $progress = $statusBar.find('.progress').hide(),

                    // 添加的文件数量
                    fileCount = 0,

                    // 添加的文件总大小
                    fileSize = 0,

                    // 优化retina, 在retina下这个值是2
                    ratio = window.devicePixelRatio || 1,

                    // 缩略图大小
                    thumbnailWidth = 110 * ratio,
                    thumbnailHeight = 110 * ratio,

                    // 可能有pedding, ready, uploading, confirm, done.
                    state = 'pedding',

                    // 所有文件的进度信息，key为file id
                    percentages = {},
                    // 判断浏览器是否支持图片的base64
                    isSupportBase64 = (function () {
                        var data = new Image();
                        var support = true;
                        data.onload = data.onerror = function () {
                            if (this.width != 1 || this.height != 1) {
                                support = false;
                            }
                        }
                        data.src = "";
                        return support;
                    })(),

                    // 检测是否已经安装flash，检测flash的版本
                    flashVersion = (function () {
                        var version;

                        try {
                            version = navigator.plugins['Shockwave Flash'];
                            version = version.description;
                        } catch (ex) {
                            try {
                                version = new ActiveXObject('ShockwaveFlash.ShockwaveFlash')
                                        .GetVariable('$version');
                            } catch (ex2) {
                                version = '0.0';
                            }
                        }
                        version = version.match(/\d+/g);
                        return parseFloat(version[0] + '.' + version[1], 10);
                    })(),

                    supportTransition = (function () {
                        var s = document.createElement('p').style,
                            r = 'transition' in s ||
                                    'WebkitTransition' in s ||
                                    'MozTransition' in s ||
                                    'msTransition' in s ||
                                    'OTransition' in s;
                        s = null;
                        return r;
                    })(),

                    // WebUploader实例
                    uploader;

                if (!WebUploader.Uploader.support('flash') && WebUploader.browser.ie) {

                    // flash 安装了但是版本过低。
                    if (flashVersion) {
                        (function (container) {
                            window['expressinstallcallback'] = function (state) {
                                switch (state) {
                                    case 'Download.Cancelled':
                                        alert('您取消了更新！')
                                        break;

                                    case 'Download.Failed':
                                        alert('安装失败')
                                        break;

                                    default:
                                        alert('安装已成功，请刷新！');
                                        break;
                                }
                                delete window['expressinstallcallback'];
                            };

                            var swf = 'expressInstall.swf';
                            // insert flash object
                            var html = '<object type="application/' +
                                    'x-shockwave-flash" data="' + swf + '" ';

                            if (WebUploader.browser.ie) {
                                html += 'classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" ';
                            }

                            html += 'width="100%" height="100%" style="outline:0">' +
                                '<param name="movie" value="' + swf + '" />' +
                                '<param name="wmode" value="transparent" />' +
                                '<param name="allowscriptaccess" value="always" />' +
                            '</object>';

                            container.html(html);

                        })($wrap);

                        // 压根就没有安转。
                    } else {
                        $wrap.html('<a href="http://www.adobe.com/go/getflashplayer" target="_blank" border="0"><img alt="get flash player" src="http://www.adobe.com/macromedia/style_guide/images/160x41_Get_Flash_Player.jpg" /></a>');
                    }

                    return;
                } else if (!WebUploader.Uploader.support()) {
                    alert('Web Uploader 不支持您的浏览器！');
                    return;
                }

                // 实例化
                uploader = WebUploader.create({
                    pick: {
                        id: '#filePicker-2',
                        label: '点击选择附件图片'
                    },
                    formData: {
                        uid: 123
                    },
                    dnd: '#dndArea',
                    paste: '#uploader',
                    swf: '../../lib/webuploader/0.1.5/Uploader.swf',
                    chunked: false,
                    chunkSize: 512 * 1024,
                    server: '../../lib/webuploader/0.1.5/server/Upload.aspx',
                    // runtimeOrder: 'flash',

                    // accept: {
                    //     title: 'Images',
                    //     extensions: 'gif,jpg,jpeg,bmp,png',
                    //     mimeTypes: 'image/*'
                    // },

                    // 禁掉全局的拖拽功能。这样不会出现图片拖进页面的时候，把图片打开。
                    disableGlobalDnd: true,
                    fileNumLimit: 300,
                    fileSizeLimit: 200 * 1024 * 1024,    // 200 M
                    fileSingleSizeLimit: 50 * 1024 * 1024    // 50 M
                });

                // 拖拽时不接受 js, txt 文件。
                uploader.on('dndAccept', function (items) {
                    var denied = false,
                        len = items.length,
                        i = 0,
                        // 修改js类型
                        unAllowed = 'text/plain;application/javascript ';

                    for (; i < len; i++) {
                        // 如果在列表里面
                        if (~unAllowed.indexOf(items[i].type)) {
                            denied = true;
                            break;
                        }
                    }

                    return !denied;
                });

                uploader.on('dialogOpen', function () {
                    console.log('here');
                });

                // uploader.on('filesQueued', function() {
                //     uploader.sort(function( a, b ) {
                //         if ( a.name < b.name )
                //           return -1;
                //         if ( a.name > b.name )
                //           return 1;
                //         return 0;
                //     });
                // });

                // 添加“添加文件”的按钮，
                uploader.addButton({
                    id: '#filePicker2',
                    label: '继续添加'
                });

                uploader.on('ready', function () {
                    window.uploader = uploader;
                    //获取数据  
                    var jsonLen='<%=md.imgs%>';  
                    if(jsonLen!=""){  
                        fileCount=jsonLen.split('|').length;    
                        $placeHolder.addClass( 'element-invisible' );  
                        $statusBar.show();  
                        //显示在页面上  
                        $.each(jsonLen.split('|'),function(i,n){  
                            var obj={},statusMap={}  
                                   ,file_id='WU_FILE_' + i;  
                            obj.id=file_id ;  
                            obj.name='';  
                            obj.filename=n;
                            obj.getStatus=function() {  
                                return '';  
                            }; 
                            obj.setStatus=function( status, text ) {  
                 
                                var prevStatus = statusMap[ this.id ];  
                                
                                typeof text !== 'undefined' && (this.statusText = text);  
                                if ( status !== prevStatus ) {  
                                    statusMap[ this.id ] = status;  
                                    /** 
                                     * 文件状态变化 
                                     * @event statuschange 
                                     */  
                                    uploader.trigger( 'statuschange', status, prevStatus );  
                                }  
              
                            };  
                            editFile(obj);  
                        });  
              
                        WebUploader.Base.idSuffix=jsonLen.split('|').length;  
              
                        setState( 'ready' );  
                        updateTotalProgress();  
                    }    
                });
                function editFile( file ) {
                    var $li = $( '<li id="' + file.id + '">' +
                            '<p class="title">' + file.name + '</p>' +
                            '<p class="imgWrap imgWrap2"></p>'+
                            '<p class="progress"><span></span></p>' +
                            '</li>' ),

                        $btns = $('<div class="file-panel">' +
                            '<span class="cancel">删除</span>' +
                            '<span class="rotateRight">向右旋转</span>' +
                            '<span class="rotateLeft">向左旋转</span></div>').appendTo( $li ),
                        $prgress = $li.find('p.progress span'),
                        $wrap = $li.find( 'p.imgWrap' ),
                        $info = $('<p class="error"></p>');

                
                    if ( file.getStatus() === 'invalid' ) {
                        showError( file.statusText );
                    } else {
                        // @todo lazyload
                        $wrap.empty();
                        $wrap.text( '不能预览' );
                
                        var img;
                        //判断是否是图片
                        //读取文件流
                        img = $('<img src="'+file.filename+'" style="height:100%;">');
                        $wrap.empty().append( img );
                
                        percentages[ file.id ] = [ file.size, 0 ];
                        file.rotation = 0;
                    }

                    $li.append( '<span class="success"></span>' );

                    $li.on( 'mouseenter', function() {
                        $btns.stop().animate({height: 30});
                    });

                    $li.on( 'mouseleave', function() {
                        $btns.stop().animate({height: 0});
                    });

                    $btns.on( 'click', 'span', function() {
                        var index = $(this).index(),
                            deg;

                        switch ( index ) {
                            case 0:
                                uploader.removeFile( file );
                                return;

                            case 1:
                                file.rotation += 90;
                                break;

                            case 2:
                                file.rotation -= 90;
                                break;
                        }

                        if ( supportTransition ) {
                            deg = 'rotate(' + file.rotation + 'deg)';
                            $wrap.css({
                                '-webkit-transform': deg,
                                '-mos-transform': deg,
                                '-o-transform': deg,
                                'transform': deg
                            });
                        } else {
                            $wrap.css( 'filter', 'progid:DXImageTransform.Microsoft.BasicImage(rotation='+ (~~((file.rotation/90)%4 + 4)%4) +')');
                        }


                    });

                    $li.appendTo( $queue );
                }
                // 当有文件添加进来时执行，负责view的创建
                function addFile(file) {
                    var $li = $('<li id="' + file.id + '">' +
                            '<p class="title">' + file.name + '</p>' +
                            '<p class="imgWrap"></p>' +
                            '<p class="progress"><span></span></p>' +
                            '</li>'),

                        $btns = $('<div class="file-panel">' +
                            '<span class="cancel">删除</span>' +
                            '<span class="rotateRight">向右旋转</span>' +
                            '<span class="rotateLeft">向左旋转</span></div>').appendTo($li),
                        $prgress = $li.find('p.progress span'),
                        $wrap = $li.find('p.imgWrap'),
                        $info = $('<p class="error"></p>'),

                        showError = function (code) {
                            switch (code) {
                                case 'exceed_size':
                                    text = '文件大小超出';
                                    break;

                                case 'interrupt':
                                    text = '上传暂停';
                                    break;

                                default:
                                    text = '上传失败，请重试';
                                    break;
                            }

                            $info.text(text).appendTo($li);
                        };

                    if (file.getStatus() === 'invalid') {
                        showError(file.statusText);
                    } else {
                        // @todo lazyload
                        $wrap.text('预览中');
                        uploader.makeThumb(file, function (error, src) {
                            var img;

                            if (error) {
                                $wrap.text('不能预览');
                                return;
                            }

                            if (isSupportBase64) {
                                img = $('<img src="' + src + '">');
                                $wrap.empty().append(img);
                            } else {
                                $.ajax('lib/webuploader/0.1.5/server/preview.php', {
                                    method: 'POST',
                                    data: src,
                                    dataType: 'json'
                                }).done(function (response) {
                                    if (response.result) {
                                        img = $('<img src="' + response.result + '">');
                                        $wrap.empty().append(img);
                                    } else {
                                        $wrap.text("预览出错");
                                    }
                                });
                            }
                        }, thumbnailWidth, thumbnailHeight);

                        percentages[file.id] = [file.size, 0];
                        file.rotation = 0;
                    }

                    file.on('statuschange', function (cur, prev) {
                        if (prev === 'progress') {
                            $prgress.hide().width(0);
                        } else if (prev === 'queued') {
                            $li.off('mouseenter mouseleave');
                            $btns.remove();
                        }

                        // 成功
                        if (cur === 'error' || cur === 'invalid') {
                            console.log(file.statusText);
                            showError(file.statusText);
                            percentages[file.id][1] = 1;
                        } else if (cur === 'interrupt') {
                            showError('interrupt');
                        } else if (cur === 'queued') {
                            percentages[file.id][1] = 0;
                        } else if (cur === 'progress') {
                            $info.remove();
                            $prgress.css('display', 'block');
                        } else if (cur === 'complete') {
                            $li.append('<span class="success"></span>');
                        }
                        $li.removeClass('state-' + prev).addClass('state-' + cur);
                    });

                    $li.on('mouseenter', function () {
                        $btns.stop().animate({ height: 30 });
                    });

                    $li.on('mouseleave', function () {
                        $btns.stop().animate({ height: 0 });
                    });

                    $btns.on('click', 'span', function () {
                        var index = $(this).index(),
                            deg;

                        switch (index) {
                            case 0:
                                uploader.removeFile(file);
                                return;

                            case 1:
                                file.rotation += 90;
                                break;

                            case 2:
                                file.rotation -= 90;
                                break;
                        }

                        if (supportTransition) {
                            deg = 'rotate(' + file.rotation + 'deg)';
                            $wrap.css({
                                '-webkit-transform': deg,
                                '-mos-transform': deg,
                                '-o-transform': deg,
                                'transform': deg
                            });
                        } else {
                            $wrap.css('filter', 'progid:DXImageTransform.Microsoft.BasicImage(rotation=' + (~~((file.rotation / 90) % 4 + 4) % 4) + ')');
                            // use jquery animate to rotation
                            // $({
                            //     rotation: rotation
                            // }).animate({
                            //     rotation: file.rotation
                            // }, {
                            //     easing: 'linear',
                            //     step: function( now ) {
                            //         now = now * Math.PI / 180;

                            //         var cos = Math.cos( now ),
                            //             sin = Math.sin( now );

                            //         $wrap.css( 'filter', "progid:DXImageTransform.Microsoft.Matrix(M11=" + cos + ",M12=" + (-sin) + ",M21=" + sin + ",M22=" + cos + ",SizingMethod='auto expand')");
                            //     }
                            // });
                        }


                    });

                    $li.appendTo($queue);
                }

                // 负责view的销毁
                function removeFile(file) {
                    var $li = $('#' + file.id);

                    delete percentages[file.id];
                    updateTotalProgress();
                    $li.off().find('.file-panel').off().end().remove();
                }

                function updateTotalProgress() {
                    var loaded = 0,
                        total = 0,
                        spans = $progress.children(),
                        percent;

                    $.each(percentages, function (k, v) {
                        total += v[0];
                        loaded += v[0] * v[1];
                    });

                    percent = total ? loaded / total : 0;


                    spans.eq(0).text(Math.round(percent * 100) + '%');
                    spans.eq(1).css('width', Math.round(percent * 100) + '%');
                    updateStatus();
                }

                function updateStatus() {
                    var text = '', stats;

                    if (state === 'ready') {
                        text = '选中' + fileCount + '张效果图';
                    } else if (state === 'confirm') {
                        stats = uploader.getStats();
                        if (stats.uploadFailNum) {
                            text = '已成功上传' + stats.successNum + '张效果图，' +
                                stats.uploadFailNum + '张效果图上传失败，<a class="retry" href="#">重新上传</a>失败效果图或<a class="ignore" href="#">忽略</a>'
                        }

                    } else {
                        stats = uploader.getStats();
                        text = '共' + fileCount + '张，已上传' + stats.successNum + '张';

                        if (stats.uploadFailNum) {
                            text += '，失败' + stats.uploadFailNum + '张';
                        }
                    }

                    $info.html(text);
                }

                function setState(val) {
                    var file, stats;

                    if (val === state) {
                        return;
                    }

                    $upload.removeClass('state-' + state);
                    $upload.addClass('state-' + val);
                    state = val;

                    switch (state) {
                        case 'pedding':
                            $placeHolder.removeClass('element-invisible');
                            $queue.hide();
                            $statusBar.addClass('element-invisible');
                            uploader.refresh();
                            break;

                        case 'ready':
                            $placeHolder.addClass('element-invisible');
                            $('#filePicker2').removeClass('element-invisible');
                            $queue.show();
                            $statusBar.removeClass('element-invisible');
                            uploader.refresh();
                            break;

                        case 'uploading':
                            $('#filePicker2').addClass('element-invisible');
                            $progress.show();
                            $upload.text('暂停上传');
                            break;

                        case 'paused':
                            $progress.show();
                            $upload.text('继续上传');
                            break;

                        case 'confirm':
                            $progress.hide();
                            $('#filePicker2').removeClass('element-invisible');
                            $upload.text('开始上传');

                            stats = uploader.getStats();
                            if (stats.successNum && !stats.uploadFailNum) {
                                setState('finish');
                                return;
                            }
                            break;
                        case 'finish':
                            stats = uploader.getStats();
                            if (stats.successNum) {
                                alert('上传成功');
                            } else {
                                // 没有成功的图片，重设
                                state = 'done';
                                location.reload();
                            }
                            break;
                    }

                    updateStatus();
                }

                uploader.onUploadProgress = function (file, percentage) {
                    var $li = $('#' + file.id),
                        $percent = $li.find('.progress span');

                    $percent.css('width', percentage * 100 + '%');
                    percentages[file.id][1] = percentage;
                    updateTotalProgress();
                };

                uploader.onFileQueued = function (file) {
                    fileCount++;
                    fileSize += file.size;

                    if (fileCount === 1) {
                        $placeHolder.addClass('element-invisible');
                        $statusBar.show();
                    }

                    addFile(file);
                    setState('ready');
                    updateTotalProgress();
                };

                uploader.onFileDequeued = function (file) {
                    fileCount--;
                    fileSize -= file.size;

                    if (!fileCount) {
                        setState('pedding');
                    }
                    removeFile(file);
                    updateTotalProgress();

                };

                uploader.on('all', function (type) {
                    var stats;
                    switch (type) {
                        case 'uploadFinished':
                            setState('confirm');
                            break;

                        case 'startUpload':
                            setState('uploading');
                            break;

                        case 'stopUpload':
                            setState('paused');
                            break;

                    }
                });
                uploader.on('uploadAccept', function (file, response) {
                    if ($("#hidurls").val() == "") {
                        $("#hidurls").val(response);
                    } else {
                        $("#hidurls").val($("#hidurls").val() + "|" + response);
                    }
                });
                uploader.onError = function (code) {
                    alert('Eroor: ' + code);
                };

                $upload.on('click', function () {
                    if ($(this).hasClass('disabled')) {
                        return false;
                    }

                    if (state === 'ready') {
                        uploader.upload();
                    } else if (state === 'paused') {
                        uploader.upload();
                    } else if (state === 'uploading') {
                        uploader.stop();
                    }
                });

                $info.on('click', '.retry', function () {
                    uploader.retry();
                });

                $info.on('click', '.ignore', function () {
                    alert('todo');
                });

                $upload.addClass('state-' + state);
                updateTotalProgress();
            });

        })(jQuery);
    </script>
</body>
</html>
